<?php

namespace app\mos\controller;

use app\common\controller\Platurl;
use app\common\model\CardMember;
use app\common\model\CardUserGet;
use app\common\model\CardGeneral;
use app\common\model\CardConsume;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\OpenTemplate;
use app\common\model\WxOpen;
use app\common\model\System;
use app\common\controller\Carddate;
use app\common\controller\AdminBase;

use think\Controller;
use think\Session;
use Wechat\Wxobjopen;

class Wxtplmesg extends Controller
{

    //模版消息余额变动
    /*
     * 参数
     * $card_id\$type\$openid\$add_balance\$balance
     *
     * */
    public function balancesendmesg($arr)
    {
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $map['id'] = $CardMember->where('card_id', $arr['card_id'])->value('mid');
        $wx_open_id = $Merchant->where($map)->value('wx_open_id');
        //初始化微信类
        $options = $this->options($arr['card_id']);
        $wxObj = new Wxobjopen($options);
        $OpenTemplate = new OpenTemplate();
        $templateid = $OpenTemplate->where(['type' => 'card_ye_tpl', 'wx_open_id' => $wx_open_id])->value('template_id');
        switch ($arr['type']) {
            case "1":
                $type = "充值";
                break;
            case "2":
                $type = "消费";
                break;
            case "3":
                $type = "奖励";
                break;
            default:
                $type = "未知";
                break;
        }
        $balance = sprintf("%.2f", substr(sprintf("%.3f", $arr['balance']), 0, -2));
        $template = array(
            'touser' => $arr['openid'],
            'template_id' => trim($templateid),
            'url' => "",
            'topcolor' => "#7B68EE",
            'data' => array(
                'first' => ['value' => '余额' . $type . "提醒", 'color' => "#743A3A"],
                'keyword1' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                'keyword2' => ['value' => '余额' . $type, 'color' => '#FF0000'],
                'keyword3' => ['value' => sprintf("%.2f", substr(sprintf("%.3f", $arr['add_balance']), 0, -2)) . '元', 'color' => '#000'],
                'keyword4' => ['value' => $balance . '元', 'color' => '#000'],
                'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
            )
        );

        $rarr['sendmsg'] = $wxObj->sendTemplateMessage($template);
//        file_put_contents('/data2/html/payos/mobile.txt', 'upbalance-1:' . json_encode($rarr).PHP_EOL, FILE_APPEND);
//        if ($res['errcode'] == 0) {
            $CardUserGet = new CardUserGet();
            $arrp['card_id'] = $arr['card_id'];
            $arrp['code'] = $CardUserGet->where(['openid' => $arr['openid'], 'card_id' => $arr['card_id']])->value('code');
            $arrp['price'] = $balance;
            $resu = $this->updateprice($arrp);
//        file_put_contents('/data2/html/payos/mobile.txt', 'upbalance-2:' . json_encode($resu).PHP_EOL, FILE_APPEND);
            $rarr['update'] = $resu;
//        } else {
//            $rarr = $res;
//        }
        return $rarr;
    }


    //余额更新
    public function updateprice($arr)
    {
        //实例化微信
        $options = $this->options($arr['card_id']);
        $WxObj = new Wxobjopen($options);
        $data = [
            'code' => $arr['code'],
            'card_id' => $arr['card_id'],
            'custom_field_value2' => $arr['price'] . '元',
            'notify_optional' => [
                'is_notify_bonus' => false,
                'is_notify_balance' => false,
                'is_notify_custom_field2' => false,
            ],
        ];
        $res = $WxObj->updateUserInfo($data);
        return $res;
    }


    //单独发送卡券
    /*
     *参数
     * $card_id\$openid\$name\$title
     */
    public function putCard($arr)
    {
        if (filteroffcard($arr['card_id']) == true) {
            $Merchant = new Merchant();
            $mid = $this->getmid($arr['card_id']);
            $wx_open_id = $Merchant->where('id', $mid)->value('wx_open_id');
            //初始化微信类
            $options = $this->options($arr['card_id']);
            $weObj = new Wxobjopen($options);
            //模板ID
            $OpenTemplate = new OpenTemplate();
            $templateid = $OpenTemplate->where(['type' => 'card_zs_tpl', 'wx_open_id' => $wx_open_id])->value('template_id');

            $Platurl = new Platurl();
            $agent_url = $Platurl->getagenturl('card_id',$arr['card_id']);

            $template = array(
                'touser' => $arr['openid'],
                'template_id' => $templateid,
                'url' => $agent_url."/mobile.php/carduser/addcard/card_id/" . $arr['card_id'] . "/openid/" . $arr['openid'],
                'topcolor' => "#7B68EE",
                'data' => array(
                    'first' => ['value' => "卡券赠送提醒", 'color' => "#743A3A"],
                    'keyword1' => ['value' => $arr['name'], 'color' => '#000'],
                    'keyword2' => ['value' => $arr['title'], 'color' => '#FF0000'],
                    'keyword3' => ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'],
                    'remark' => ['value' => "祝您生活愉快", 'color' => '#000'],
                )
            );
            $res = $weObj->sendTemplateMessage($template);
            return $res;
        }
    }

    //商户ID
    /*
     *参数
     * $card_id
     */
    public function getmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent=new Agent();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo= $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] =$merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }
}
